<!DOCTYPE html>
<html lang="zh">
<head>
    <meta http-equiv="content-type" content="text/html;charset=utf-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    <meta name="description" content="使用冻结 BERT 模型为区块生成 BERT 嵌入"/>

    <meta name="twitter:card" content="summary"/>
    <meta name="twitter:image:src" content="https://avatars1.githubusercontent.com/u/64068543?s=400&amp;v=4"/>
    <meta name="twitter:title" content="BERT 文本块的嵌入"/>
    <meta name="twitter:description" content="使用冻结 BERT 模型为区块生成 BERT 嵌入"/>
    <meta name="twitter:site" content="@labmlai"/>
    <meta name="twitter:creator" content="@labmlai"/>

    <meta property="og:url" content="https://nn.labml.ai/transformers/retro/bert_embeddings.html"/>
    <meta property="og:title" content="BERT 文本块的嵌入"/>
    <meta property="og:image" content="https://avatars1.githubusercontent.com/u/64068543?s=400&amp;v=4"/>
    <meta property="og:site_name" content="BERT 文本块的嵌入"/>
    <meta property="og:type" content="object"/>
    <meta property="og:title" content="BERT 文本块的嵌入"/>
    <meta property="og:description" content="使用冻结 BERT 模型为区块生成 BERT 嵌入"/>

    <title>BERT 文本块的嵌入</title>
    <link rel="shortcut icon" href="/icon.png"/>
    <link rel="stylesheet" href="../../pylit.css?v=1">
    <link rel="canonical" href="https://nn.labml.ai/transformers/retro/bert_embeddings.html"/>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.13.18/dist/katex.min.css" integrity="sha384-zTROYFVGOfTw7JV7KUu8udsvW2fx4lWOsCEDqhBreBwlHI4ioVRtmIvEThzJHGET" crossorigin="anonymous">

    <!-- Global site tag (gtag.js) - Google Analytics -->
    <script async src="https://www.googletagmanager.com/gtag/js?id=G-4V3HC8HBLH"></script>
    <script>
        window.dataLayer = window.dataLayer || [];

        function gtag() {
            dataLayer.push(arguments);
        }

        gtag('js', new Date());

        gtag('config', 'G-4V3HC8HBLH');
    </script>
</head>
<body>
<div id='container'>
    <div id="background"></div>
    <div class='section'>
        <div class='docs'>
            <p>
                <a class="parent" href="/">home</a>
                <a class="parent" href="../index.html">transformers</a>
                <a class="parent" href="index.html">retro</a>
            </p>
            <p>
                <a href="https://github.com/labmlai/annotated_deep_learning_paper_implementations" target="_blank">
                    <img alt="Github"
                         src="https://img.shields.io/github/stars/labmlai/annotated_deep_learning_paper_implementations?style=social"
                         style="max-width:100%;"/></a>
                <a href="https://twitter.com/labmlai" rel="nofollow" target="_blank">
                    <img alt="Twitter"
                         src="https://img.shields.io/twitter/follow/labmlai?style=social"
                         style="max-width:100%;"/></a>
            </p>
            <p>
                <a href="https://github.com/labmlai/annotated_deep_learning_paper_implementations/tree/master/labml_nn/transformers/retro/bert_embeddings.py" target="_blank">
                    View code on Github</a>
            </p>
        </div>
    </div>
    <div class='section' id='section-0'>
        <div class='docs doc-strings'>
            <div class='section-link'>
                <a href='#section-0'>#</a>
            </div>
            <h1>BERT 文本块的嵌入</h1>
<p>这是获取 <a href="index.html">RETRO 模型</a>块的 BERT 嵌入的代码。</p>

        </div>
        <div class='code'>
            <div class="highlight"><pre><span class="lineno">13</span><span></span><span class="kn">from</span> <span class="nn">typing</span> <span class="kn">import</span> <span class="n">List</span>
<span class="lineno">14</span>
<span class="lineno">15</span><span class="kn">import</span> <span class="nn">torch</span>
<span class="lineno">16</span><span class="kn">from</span> <span class="nn">transformers</span> <span class="kn">import</span> <span class="n">BertTokenizer</span><span class="p">,</span> <span class="n">BertModel</span>
<span class="lineno">17</span>
<span class="lineno">18</span><span class="kn">from</span> <span class="nn">labml</span> <span class="kn">import</span> <span class="n">lab</span><span class="p">,</span> <span class="n">monit</span></pre></div>
        </div>
    </div>
    <div class='section' id='section-1'>
        <div class='docs doc-strings'>
            <div class='section-link'>
                <a href='#section-1'>#</a>
            </div>
            <h2>BERT 嵌入式</h2>
<p>对于给定的文本块，<span ><span class="katex"><span aria-hidden="true" class="katex-html"><span class="base"><span class="strut" style="height:0.68333em;vertical-align:0em;"></span><span class="mord coloredeq eqb" style=""><span class="mord mathnormal" style="margin-right:0.10903em">N</span></span></span></span></span></span>这个类会生成 BERT 嵌入<span ><span class="katex"><span aria-hidden="true" class="katex-html"><span class="base"><span class="strut" style="height:1em;vertical-align:-0.25em;"></span><span class="mord coloredeq eqa" style=""><span class="mord text" style=""><span class="mord" style="">B</span><span class="mord sizing reset-size6 size5" style=""><span class="mord" style="">ERT</span></span></span><span class="mopen" style="">(</span><span class="mord" style=""><span class="mord mathnormal coloredeq eqb" style="margin-right:0.10903em">N</span></span><span class="mclose" style="">)</span></span></span></span></span></span>。<span ><span class="katex"><span aria-hidden="true" class="katex-html"><span class="base"><span class="strut" style="height:1em;vertical-align:-0.25em;"></span><span class="mord coloredeq eqa" style=""><span class="mord text" style=""><span class="mord" style="">B</span><span class="mord sizing reset-size6 size5" style=""><span class="mord" style="">ERT</span></span></span><span class="mopen" style="">(</span><span class="mord" style=""><span class="mord mathnormal coloredeq eqb" style="margin-right:0.10903em">N</span></span><span class="mclose" style="">)</span></span></span></span></span></span>是所有令牌的 BERT 嵌入的平均值<span ><span class="katex"><span aria-hidden="true" class="katex-html"><span class="base"><span class="strut" style="height:0.68333em;vertical-align:0em;"></span><span class="mord coloredeq eqb" style=""><span class="mord mathnormal" style="margin-right:0.10903em">N</span></span></span></span></span></span>。</p>

        </div>
        <div class='code'>
            <div class="highlight"><pre><span class="lineno">21</span><span class="k">class</span> <span class="nc">BERTChunkEmbeddings</span><span class="p">:</span></pre></div>
        </div>
    </div>
    <div class='section' id='section-2'>
        <div class='docs'>
            <div class='section-link'>
                <a href='#section-2'>#</a>
            </div>
            
        </div>
        <div class='code'>
            <div class="highlight"><pre><span class="lineno">29</span>    <span class="k">def</span> <span class="fm">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">device</span><span class="p">:</span> <span class="n">torch</span><span class="o">.</span><span class="n">device</span><span class="p">):</span>
<span class="lineno">30</span>        <span class="bp">self</span><span class="o">.</span><span class="n">device</span> <span class="o">=</span> <span class="n">device</span></pre></div>
        </div>
    </div>
    <div class='section' id='section-3'>
        <div class='docs'>
            <div class='section-link'>
                <a href='#section-3'>#</a>
            </div>
            <p>从 <a href="https://huggingface.co/bert-base-uncased">HuggingFac</a> e 加载 BERT 分词器</p>

        </div>
        <div class='code'>
            <div class="highlight"><pre><span class="lineno">33</span>        <span class="k">with</span> <span class="n">monit</span><span class="o">.</span><span class="n">section</span><span class="p">(</span><span class="s1">&#39;Load BERT tokenizer&#39;</span><span class="p">):</span>
<span class="lineno">34</span>            <span class="bp">self</span><span class="o">.</span><span class="n">tokenizer</span> <span class="o">=</span> <span class="n">BertTokenizer</span><span class="o">.</span><span class="n">from_pretrained</span><span class="p">(</span><span class="s1">&#39;bert-base-uncased&#39;</span><span class="p">,</span>
<span class="lineno">35</span>                                                           <span class="n">cache_dir</span><span class="o">=</span><span class="nb">str</span><span class="p">(</span>
<span class="lineno">36</span>                                                               <span class="n">lab</span><span class="o">.</span><span class="n">get_data_path</span><span class="p">()</span> <span class="o">/</span> <span class="s1">&#39;cache&#39;</span> <span class="o">/</span> <span class="s1">&#39;bert-tokenizer&#39;</span><span class="p">))</span></pre></div>
        </div>
    </div>
    <div class='section' id='section-4'>
        <div class='docs'>
            <div class='section-link'>
                <a href='#section-4'>#</a>
            </div>
            <p>从 <a href="https://huggingface.co/bert-base-uncased">HuggingFac</a> e 加载 BERT 模型</p>

        </div>
        <div class='code'>
            <div class="highlight"><pre><span class="lineno">39</span>        <span class="k">with</span> <span class="n">monit</span><span class="o">.</span><span class="n">section</span><span class="p">(</span><span class="s1">&#39;Load BERT model&#39;</span><span class="p">):</span>
<span class="lineno">40</span>            <span class="bp">self</span><span class="o">.</span><span class="n">model</span> <span class="o">=</span> <span class="n">BertModel</span><span class="o">.</span><span class="n">from_pretrained</span><span class="p">(</span><span class="s2">&quot;bert-base-uncased&quot;</span><span class="p">,</span>
<span class="lineno">41</span>                                                   <span class="n">cache_dir</span><span class="o">=</span><span class="nb">str</span><span class="p">(</span><span class="n">lab</span><span class="o">.</span><span class="n">get_data_path</span><span class="p">()</span> <span class="o">/</span> <span class="s1">&#39;cache&#39;</span> <span class="o">/</span> <span class="s1">&#39;bert-model&#39;</span><span class="p">))</span></pre></div>
        </div>
    </div>
    <div class='section' id='section-5'>
        <div class='docs'>
            <div class='section-link'>
                <a href='#section-5'>#</a>
            </div>
            <p>将模型移到<code  class="highlight"><span></span><span class="n">device</span></code>
</p>

        </div>
        <div class='code'>
            <div class="highlight"><pre><span class="lineno">44</span>            <span class="bp">self</span><span class="o">.</span><span class="n">model</span><span class="o">.</span><span class="n">to</span><span class="p">(</span><span class="n">device</span><span class="p">)</span></pre></div>
        </div>
    </div>
    <div class='section' id='section-6'>
        <div class='docs doc-strings'>
            <div class='section-link'>
                <a href='#section-6'>#</a>
            </div>
            <p>在此实现中，我们不会使用固定数量的令牌制作区块。原因之一是此实现使用字符级令牌，而 BERT 使用其子词分词器。</p>
<p>因此，此方法将截断文本以确保没有部分标记。</p>
<p>例如，一个块可能像<code  class="highlight"><span></span><span class="n">s</span> <span class="n">a</span> <span class="n">popular</span> <span class="n">programming</span> <span class="n">la</span></code>
，末尾带有部分单词（部分子词标记）。我们剥离它们以获得更好的 BERT 嵌入。如前所述，如果我们在标记化后破坏了区块，则没有必要这样做。</p>

        </div>
        <div class='code'>
            <div class="highlight"><pre><span class="lineno">46</span>    <span class="nd">@staticmethod</span>
<span class="lineno">47</span>    <span class="k">def</span> <span class="nf">_trim_chunk</span><span class="p">(</span><span class="n">chunk</span><span class="p">:</span> <span class="nb">str</span><span class="p">):</span></pre></div>
        </div>
    </div>
    <div class='section' id='section-7'>
        <div class='docs'>
            <div class='section-link'>
                <a href='#section-7'>#</a>
            </div>
            <p>去掉空白</p>

        </div>
        <div class='code'>
            <div class="highlight"><pre><span class="lineno">61</span>        <span class="n">stripped</span> <span class="o">=</span> <span class="n">chunk</span><span class="o">.</span><span class="n">strip</span><span class="p">()</span></pre></div>
        </div>
    </div>
    <div class='section' id='section-8'>
        <div class='docs'>
            <div class='section-link'>
                <a href='#section-8'>#</a>
            </div>
            <p>断词</p>

        </div>
        <div class='code'>
            <div class="highlight"><pre><span class="lineno">63</span>        <span class="n">parts</span> <span class="o">=</span> <span class="n">stripped</span><span class="o">.</span><span class="n">split</span><span class="p">()</span></pre></div>
        </div>
    </div>
    <div class='section' id='section-9'>
        <div class='docs'>
            <div class='section-link'>
                <a href='#section-9'>#</a>
            </div>
            <p>移除第一块和最后一块碎片</p>

        </div>
        <div class='code'>
            <div class="highlight"><pre><span class="lineno">65</span>        <span class="n">stripped</span> <span class="o">=</span> <span class="n">stripped</span><span class="p">[</span><span class="nb">len</span><span class="p">(</span><span class="n">parts</span><span class="p">[</span><span class="mi">0</span><span class="p">]):</span><span class="o">-</span><span class="nb">len</span><span class="p">(</span><span class="n">parts</span><span class="p">[</span><span class="o">-</span><span class="mi">1</span><span class="p">])]</span></pre></div>
        </div>
    </div>
    <div class='section' id='section-10'>
        <div class='docs'>
            <div class='section-link'>
                <a href='#section-10'>#</a>
            </div>
            <p>移除空格</p>

        </div>
        <div class='code'>
            <div class="highlight"><pre><span class="lineno">68</span>        <span class="n">stripped</span> <span class="o">=</span> <span class="n">stripped</span><span class="o">.</span><span class="n">strip</span><span class="p">()</span></pre></div>
        </div>
    </div>
    <div class='section' id='section-11'>
        <div class='docs'>
            <div class='section-link'>
                <a href='#section-11'>#</a>
            </div>
            <p>如果为空则返回原始字符串</p>

        </div>
        <div class='code'>
            <div class="highlight"><pre><span class="lineno">71</span>        <span class="k">if</span> <span class="ow">not</span> <span class="n">stripped</span><span class="p">:</span>
<span class="lineno">72</span>            <span class="k">return</span> <span class="n">chunk</span></pre></div>
        </div>
    </div>
    <div class='section' id='section-12'>
        <div class='docs'>
            <div class='section-link'>
                <a href='#section-12'>#</a>
            </div>
            <p>否则，返回被剥离的字符串</p>

        </div>
        <div class='code'>
            <div class="highlight"><pre><span class="lineno">74</span>        <span class="k">else</span><span class="p">:</span>
<span class="lineno">75</span>            <span class="k">return</span> <span class="n">stripped</span></pre></div>
        </div>
    </div>
    <div class='section' id='section-13'>
        <div class='docs doc-strings'>
            <div class='section-link'>
                <a href='#section-13'>#</a>
            </div>
            <h3><span ><span class="katex"><span aria-hidden="true" class="katex-html"><span class="base"><span class="strut" style="height:1em;vertical-align:-0.25em;"></span><span class="mord coloredeq eqa" style=""><span class="mord text" style=""><span class="mord" style="">B</span><span class="mord sizing reset-size6 size5" style=""><span class="mord" style="">ERT</span></span></span><span class="mopen" style="">(</span><span class="mord" style=""><span class="mord mathnormal coloredeq eqb" style="margin-right:0.10903em">N</span></span><span class="mclose" style="">)</span></span></span></span></span></span>获取区块列表。</h3>

        </div>
        <div class='code'>
            <div class="highlight"><pre><span class="lineno">77</span>    <span class="k">def</span> <span class="fm">__call__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">chunks</span><span class="p">:</span> <span class="n">List</span><span class="p">[</span><span class="nb">str</span><span class="p">]):</span></pre></div>
        </div>
    </div>
    <div class='section' id='section-14'>
        <div class='docs'>
            <div class='section-link'>
                <a href='#section-14'>#</a>
            </div>
            <p>我们不需要计算梯度</p>

        </div>
        <div class='code'>
            <div class="highlight"><pre><span class="lineno">83</span>        <span class="k">with</span> <span class="n">torch</span><span class="o">.</span><span class="n">no_grad</span><span class="p">():</span></pre></div>
        </div>
    </div>
    <div class='section' id='section-15'>
        <div class='docs'>
            <div class='section-link'>
                <a href='#section-15'>#</a>
            </div>
            <p>修剪块</p>

        </div>
        <div class='code'>
            <div class="highlight"><pre><span class="lineno">85</span>            <span class="n">trimmed_chunks</span> <span class="o">=</span> <span class="p">[</span><span class="bp">self</span><span class="o">.</span><span class="n">_trim_chunk</span><span class="p">(</span><span class="n">c</span><span class="p">)</span> <span class="k">for</span> <span class="n">c</span> <span class="ow">in</span> <span class="n">chunks</span><span class="p">]</span></pre></div>
        </div>
    </div>
    <div class='section' id='section-16'>
        <div class='docs'>
            <div class='section-link'>
                <a href='#section-16'>#</a>
            </div>
            <p>使用 BERT 分词器对区块进行标记化</p>

        </div>
        <div class='code'>
            <div class="highlight"><pre><span class="lineno">88</span>            <span class="n">tokens</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">tokenizer</span><span class="p">(</span><span class="n">trimmed_chunks</span><span class="p">,</span> <span class="n">return_tensors</span><span class="o">=</span><span class="s1">&#39;pt&#39;</span><span class="p">,</span> <span class="n">add_special_tokens</span><span class="o">=</span><span class="kc">False</span><span class="p">,</span> <span class="n">padding</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span></pre></div>
        </div>
    </div>
    <div class='section' id='section-17'>
        <div class='docs'>
            <div class='section-link'>
                <a href='#section-17'>#</a>
            </div>
            <p>将令牌 ID、注意掩码和令牌类型移动到设备</p>

        </div>
        <div class='code'>
            <div class="highlight"><pre><span class="lineno">91</span>            <span class="n">input_ids</span> <span class="o">=</span> <span class="n">tokens</span><span class="p">[</span><span class="s1">&#39;input_ids&#39;</span><span class="p">]</span><span class="o">.</span><span class="n">to</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">device</span><span class="p">)</span>
<span class="lineno">92</span>            <span class="n">attention_mask</span> <span class="o">=</span> <span class="n">tokens</span><span class="p">[</span><span class="s1">&#39;attention_mask&#39;</span><span class="p">]</span><span class="o">.</span><span class="n">to</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">device</span><span class="p">)</span>
<span class="lineno">93</span>            <span class="n">token_type_ids</span> <span class="o">=</span> <span class="n">tokens</span><span class="p">[</span><span class="s1">&#39;token_type_ids&#39;</span><span class="p">]</span><span class="o">.</span><span class="n">to</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">device</span><span class="p">)</span></pre></div>
        </div>
    </div>
    <div class='section' id='section-18'>
        <div class='docs'>
            <div class='section-link'>
                <a href='#section-18'>#</a>
            </div>
            <p>评估模型</p>

        </div>
        <div class='code'>
            <div class="highlight"><pre><span class="lineno">95</span>            <span class="n">output</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">model</span><span class="p">(</span><span class="n">input_ids</span><span class="o">=</span><span class="n">input_ids</span><span class="p">,</span>
<span class="lineno">96</span>                                <span class="n">attention_mask</span><span class="o">=</span><span class="n">attention_mask</span><span class="p">,</span>
<span class="lineno">97</span>                                <span class="n">token_type_ids</span><span class="o">=</span><span class="n">token_type_ids</span><span class="p">)</span></pre></div>
        </div>
    </div>
    <div class='section' id='section-19'>
        <div class='docs'>
            <div class='section-link'>
                <a href='#section-19'>#</a>
            </div>
            <p>获取令牌嵌入</p>

        </div>
        <div class='code'>
            <div class="highlight"><pre><span class="lineno">100</span>            <span class="n">state</span> <span class="o">=</span> <span class="n">output</span><span class="p">[</span><span class="s1">&#39;last_hidden_state&#39;</span><span class="p">]</span></pre></div>
        </div>
    </div>
    <div class='section' id='section-20'>
        <div class='docs'>
            <div class='section-link'>
                <a href='#section-20'>#</a>
            </div>
            <p>计算平均代币嵌入量。请注意，<code  class="highlight"><span></span><span class="mi">0</span></code>
如果令牌是空填充的，则注意掩码为。我们得到空令牌，因为这些块的长度不同。</p>

        </div>
        <div class='code'>
            <div class="highlight"><pre><span class="lineno">104</span>            <span class="n">emb</span> <span class="o">=</span> <span class="p">(</span><span class="n">state</span> <span class="o">*</span> <span class="n">attention_mask</span><span class="p">[:,</span> <span class="p">:,</span> <span class="kc">None</span><span class="p">])</span><span class="o">.</span><span class="n">sum</span><span class="p">(</span><span class="n">dim</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span> <span class="o">/</span> <span class="n">attention_mask</span><span class="p">[:,</span> <span class="p">:,</span> <span class="kc">None</span><span class="p">]</span><span class="o">.</span><span class="n">sum</span><span class="p">(</span><span class="n">dim</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span></pre></div>
        </div>
    </div>
    <div class='section' id='section-21'>
        <div class='docs'>
            <div class='section-link'>
                <a href='#section-21'>#</a>
            </div>
            <p></p>

        </div>
        <div class='code'>
            <div class="highlight"><pre><span class="lineno">107</span>            <span class="k">return</span> <span class="n">emb</span></pre></div>
        </div>
    </div>
    <div class='section' id='section-22'>
        <div class='docs doc-strings'>
            <div class='section-link'>
                <a href='#section-22'>#</a>
            </div>
            <h3>用于测试 BERT 嵌入的代码</h3>

        </div>
        <div class='code'>
            <div class="highlight"><pre><span class="lineno">110</span><span class="k">def</span> <span class="nf">_test</span><span class="p">():</span></pre></div>
        </div>
    </div>
    <div class='section' id='section-23'>
        <div class='docs'>
            <div class='section-link'>
                <a href='#section-23'>#</a>
            </div>
            
        </div>
        <div class='code'>
            <div class="highlight"><pre><span class="lineno">114</span>    <span class="kn">from</span> <span class="nn">labml.logger</span> <span class="kn">import</span> <span class="n">inspect</span></pre></div>
        </div>
    </div>
    <div class='section' id='section-24'>
        <div class='docs'>
            <div class='section-link'>
                <a href='#section-24'>#</a>
            </div>
            <p>初始化</p>

        </div>
        <div class='code'>
            <div class="highlight"><pre><span class="lineno">117</span>    <span class="n">device</span> <span class="o">=</span> <span class="n">torch</span><span class="o">.</span><span class="n">device</span><span class="p">(</span><span class="s1">&#39;cuda:0&#39;</span><span class="p">)</span>
<span class="lineno">118</span>    <span class="n">bert</span> <span class="o">=</span> <span class="n">BERTChunkEmbeddings</span><span class="p">(</span><span class="n">device</span><span class="p">)</span></pre></div>
        </div>
    </div>
    <div class='section' id='section-25'>
        <div class='docs'>
            <div class='section-link'>
                <a href='#section-25'>#</a>
            </div>
            <p>样本</p>

        </div>
        <div class='code'>
            <div class="highlight"><pre><span class="lineno">121</span>    <span class="n">text</span> <span class="o">=</span> <span class="p">[</span><span class="s2">&quot;Replace me by any text you&#39;d like.&quot;</span><span class="p">,</span>
<span class="lineno">122</span>            <span class="s2">&quot;Second sentence&quot;</span><span class="p">]</span></pre></div>
        </div>
    </div>
    <div class='section' id='section-26'>
        <div class='docs'>
            <div class='section-link'>
                <a href='#section-26'>#</a>
            </div>
            <p>查看 BERT 分词器</p>

        </div>
        <div class='code'>
            <div class="highlight"><pre><span class="lineno">125</span>    <span class="n">encoded_input</span> <span class="o">=</span> <span class="n">bert</span><span class="o">.</span><span class="n">tokenizer</span><span class="p">(</span><span class="n">text</span><span class="p">,</span> <span class="n">return_tensors</span><span class="o">=</span><span class="s1">&#39;pt&#39;</span><span class="p">,</span> <span class="n">add_special_tokens</span><span class="o">=</span><span class="kc">False</span><span class="p">,</span> <span class="n">padding</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
<span class="lineno">126</span>
<span class="lineno">127</span>    <span class="n">inspect</span><span class="p">(</span><span class="n">encoded_input</span><span class="p">,</span> <span class="n">_expand</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span></pre></div>
        </div>
    </div>
    <div class='section' id='section-27'>
        <div class='docs'>
            <div class='section-link'>
                <a href='#section-27'>#</a>
            </div>
            <p>检查 BERT 模型输出</p>

        </div>
        <div class='code'>
            <div class="highlight"><pre><span class="lineno">130</span>    <span class="n">output</span> <span class="o">=</span> <span class="n">bert</span><span class="o">.</span><span class="n">model</span><span class="p">(</span><span class="n">input_ids</span><span class="o">=</span><span class="n">encoded_input</span><span class="p">[</span><span class="s1">&#39;input_ids&#39;</span><span class="p">]</span><span class="o">.</span><span class="n">to</span><span class="p">(</span><span class="n">device</span><span class="p">),</span>
<span class="lineno">131</span>                        <span class="n">attention_mask</span><span class="o">=</span><span class="n">encoded_input</span><span class="p">[</span><span class="s1">&#39;attention_mask&#39;</span><span class="p">]</span><span class="o">.</span><span class="n">to</span><span class="p">(</span><span class="n">device</span><span class="p">),</span>
<span class="lineno">132</span>                        <span class="n">token_type_ids</span><span class="o">=</span><span class="n">encoded_input</span><span class="p">[</span><span class="s1">&#39;token_type_ids&#39;</span><span class="p">]</span><span class="o">.</span><span class="n">to</span><span class="p">(</span><span class="n">device</span><span class="p">))</span>
<span class="lineno">133</span>
<span class="lineno">134</span>    <span class="n">inspect</span><span class="p">({</span><span class="s1">&#39;last_hidden_state&#39;</span><span class="p">:</span> <span class="n">output</span><span class="p">[</span><span class="s1">&#39;last_hidden_state&#39;</span><span class="p">],</span>
<span class="lineno">135</span>             <span class="s1">&#39;pooler_output&#39;</span><span class="p">:</span> <span class="n">output</span><span class="p">[</span><span class="s1">&#39;pooler_output&#39;</span><span class="p">]},</span>
<span class="lineno">136</span>            <span class="n">_expand</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span></pre></div>
        </div>
    </div>
    <div class='section' id='section-28'>
        <div class='docs'>
            <div class='section-link'>
                <a href='#section-28'>#</a>
            </div>
            <p>检查从令牌 ID 中重新创建文本</p>

        </div>
        <div class='code'>
            <div class="highlight"><pre><span class="lineno">139</span>    <span class="n">inspect</span><span class="p">(</span><span class="n">bert</span><span class="o">.</span><span class="n">tokenizer</span><span class="o">.</span><span class="n">convert_ids_to_tokens</span><span class="p">(</span><span class="n">encoded_input</span><span class="p">[</span><span class="s1">&#39;input_ids&#39;</span><span class="p">][</span><span class="mi">0</span><span class="p">]),</span> <span class="n">_n</span><span class="o">=-</span><span class="mi">1</span><span class="p">)</span>
<span class="lineno">140</span>    <span class="n">inspect</span><span class="p">(</span><span class="n">bert</span><span class="o">.</span><span class="n">tokenizer</span><span class="o">.</span><span class="n">convert_ids_to_tokens</span><span class="p">(</span><span class="n">encoded_input</span><span class="p">[</span><span class="s1">&#39;input_ids&#39;</span><span class="p">][</span><span class="mi">1</span><span class="p">]),</span> <span class="n">_n</span><span class="o">=-</span><span class="mi">1</span><span class="p">)</span></pre></div>
        </div>
    </div>
    <div class='section' id='section-29'>
        <div class='docs'>
            <div class='section-link'>
                <a href='#section-29'>#</a>
            </div>
            <p>获取区块嵌入</p>

        </div>
        <div class='code'>
            <div class="highlight"><pre><span class="lineno">143</span>    <span class="n">inspect</span><span class="p">(</span><span class="n">bert</span><span class="p">(</span><span class="n">text</span><span class="p">))</span></pre></div>
        </div>
    </div>
    <div class='section' id='section-30'>
        <div class='docs'>
            <div class='section-link'>
                <a href='#section-30'>#</a>
            </div>
            <p></p>

        </div>
        <div class='code'>
            <div class="highlight"><pre><span class="lineno">147</span><span class="k">if</span> <span class="vm">__name__</span> <span class="o">==</span> <span class="s1">&#39;__main__&#39;</span><span class="p">:</span>
<span class="lineno">148</span>    <span class="n">_test</span><span class="p">()</span></pre></div>
        </div>
    </div>
    <div class='footer'>
        <a href="https://labml.ai">labml.ai</a>
    </div>
</div>
<script src=../../interactive.js?v=1"></script>
<script>
    function handleImages() {
        var images = document.querySelectorAll('p>img')

        for (var i = 0; i < images.length; ++i) {
            handleImage(images[i])
        }
    }

    function handleImage(img) {
        img.parentElement.style.textAlign = 'center'

        var modal = document.createElement('div')
        modal.id = 'modal'

        var modalContent = document.createElement('div')
        modal.appendChild(modalContent)

        var modalImage = document.createElement('img')
        modalContent.appendChild(modalImage)

        var span = document.createElement('span')
        span.classList.add('close')
        span.textContent = 'x'
        modal.appendChild(span)

        img.onclick = function () {
            console.log('clicked')
            document.body.appendChild(modal)
            modalImage.src = img.src
        }

        span.onclick = function () {
            document.body.removeChild(modal)
        }
    }

    handleImages()
</script>
</body>
</html>